# -*- coding: utf-8 -*-
# author:  qiufengfeng
# contact: fengfeng.qiu@amh-group.com
# datetime:2023/6/13 18:31

"""
文件说明：

"""
import pandas as pd
import requests
import json

import bs4

def get_juge_result(feature):
    post_url = "http://127.0.0.1:8000/phantom/torch-predict"#"https://predict-phantom.amh-group.com/short-specific-judge/v1/models/short-specific-judge:predict" #"http://127.0.0.1:8000/phantom/torch-predict"

    post_body = feature#json.loads(feature)

    headers = {
        'Content-Type': "application/json"
    }
    success_code = 0
    while success_code != 200:
        req = requests.post(post_url, json=post_body, headers=headers)
        success_code = req.status_code
    return req.json()



def make_check_data():
    df = pd.read_csv(file,sep='\001')

    df["juge_result"] = df['feature'].apply(get_juge_result)



    df.to_csv("temp.csv")




def make_output(order_id,old_result,new_result):
    print("\n########")
    print("order_id:" + str(order_id))
    print("order_result:" + old_result)
    print("new_result:" + json.dumps(new_result["importantFeatureList"],ensure_ascii=False) )
    print("new_result log :" + json.dumps(new_result['judge_logger_info']['司机抢错单日志'],indent=4,ensure_ascii=False))

def online_data_check():
    '''直接读取撸数平台的https://dt.amh-group.com/lushu/#/home数据'''
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.common.by import By
    #driver = webdriver.Chrome(r'D:\工作相关内容\公司项目\Validate\data\webdriver\chromedriver.exe')
    options = Options()
    options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    driver = webdriver.Chrome(executable_path=r'D:\工作相关内容\公司项目\Validate\data\webdriver\chromedriver.exe',chrome_options=options)
    #driver.get('https://dt.amh-group.com/lushu/#/home')

    trs = driver.find_elements(By.XPATH,"//tr[contains(@class,'el-table__row')]/td[3]")
    features = [tr.text for tr in trs]

    trs = driver.find_elements(By.XPATH, "//tr[contains(@class,'el-table__row')]/td[7]")
    order_ids = [tr.text for tr in trs]

    trs = driver.find_elements(By.XPATH, "//tr[contains(@class,'el-table__row')]/td[6]")
    results = [tr.text for tr in trs]

    print(json.loads(features[0].replace("\"\"","\"")[1:-1]))
    features = [json.loads(feature.replace("\"\"","\"")[1:-1]) for feature in features]


    for index, (order_id,feature,result) in enumerate(zip(order_ids,features,results)):
        #feature = json.loads(json.dumps(feature).lower())
        #print(json.dumps(feature))
        if "unreasonable" in feature:
            del feature["unreasonable"]
        new_result = get_juge_result(feature)
        callTexts = feature['calllogtexts']
        make_output(order_id,result,new_result)


def format_dialogue(dialogues):
    final_dialogue = []
    for dia in dialogues:
        content = dia['content']
        final_dialogue.extend(content.split("$_$"))

    return "\n".join(final_dialogue)


def make_predict_sop(newFeatureLog,check_label):
    outString = ""
    if check_label+"日志" in newFeatureLog:
        sortedResult = sorted(newFeatureLog[check_label+"日志"],key = lambda x:x["hitPriority"])


        for item in sortedResult:
            outString += "{hitType}:{hitValue}\n".format(hitType=item['hitType'],hitValue=item["hitValue"])
    return outString


def get_order_id(item):
    feature = json.loads(item["feature"])

    order_id = int(feature["orderid"])
    return order_id
def offline_data_check(file_name,check_label):
    df = pd.read_csv(file_name,sep='\001')
    df = df.sample(frac=1.0)
    df.dropna(inplace=True)


    count = 0
    saveOrderIds = []
    saveCallTexts = []
    saveOldFeature = []
    saveNewFeature = []
    saveNewFeatureLogInfo = []



    saveNear = []
    saveLastCall = []
    print(df.columns)
    print(df.head())

    df['orderid'] = df.apply(get_order_id,axis=1)
    df = df.sample(frac=1.0)
    #df = df[df['day'] == 20231010]
    print(df.head())


    # tempFile = r'D:\工作相关内容\公司项目\智能机器人\智能判责\司机抢错单(1).xlsx'
    # usedOrderIds = pd.read_excel(tempFile)["订单号"][:50].tolist()
    #
    #
    # for checkOrder in usedOrderIds:
    #     df_temp = df[df['orderid'].isin([checkOrder])]

    #df= df[df['orderid'] == 36632538381994112]
    for row in df.iterrows():
        feature = json.loads(row[1]["feature"])

        order_id = feature["orderid"]
        biz_code = feature["bizcode"]

        if biz_code != "CANCEL_CARPOOL" and biz_code != "C_SS_CARPOOL":
            continue
        callTexts = format_dialogue(feature['calllogtexts'])
        oldFeature = row[1]["importantfeaturelist"]



        if "unreasonable" in feature:
            del feature["unreasonable"]


        old_result = "是" if check_label in str(oldFeature) else "否"
        # if old_result != "是":
        #     continue

        newResult = get_juge_result(feature)
        if "importantFeatureList" not in newResult:
            continue
        newFeature = newResult["importantFeatureList"]
        newFeatureLog = newResult["judge_logger_info"]

        if "dialogue日志" in newResult['judge_logger_info']:
            callTexts = "\n".join(newResult['judge_logger_info']["dialogue日志"].split("$_$"))


        old_result = "是" if check_label in str(oldFeature) else "否"
        new_result = "是" if check_label in str(newFeature) else "否"
        # if newFeature:
        #     new_result = "是"



        if new_result == "是":
            count += 1
            saveOrderIds.append(str(order_id))
            saveCallTexts.append(callTexts)
            saveOldFeature.append(old_result)
            saveNewFeature.append(newFeature)
            saveNewFeatureLogInfo.append(make_predict_sop(newFeatureLog,check_label))
            if count >= 100:
                break
            print(count)


    daveDf = pd.DataFrame({
        "订单号":saveOrderIds
        ,"通话文本":saveCallTexts
        #,"线上识别结果":saveOldFeature
        ,"新逻辑识别标签":saveNewFeature
        ,"新逻辑识别标签SOP":saveNewFeatureLogInfo
    })
    daveDf.to_excel(check_label+".xlsx")





def get_order_id(item):
    feature = json.loads(item["feature"])

    order_id = feature["orderid"]
    return order_id


def make_shuangyue_predict_sop(newFeatureLog):
    sortedResult = sorted(newFeatureLog["司机爽约日志"],key = lambda x:x["hitPriority"])

    outString = ""
    for item in sortedResult:
        outString += "{hitType}:{hitValue}\n".format(hitType=item['hitType'],hitValue=item["hitValue"])
    return outString

def recheck(file_name,check_label):
    recheck_file_path = r'D:\工作相关内容\公司项目\智能机器人\客服SOP\司机抢错单2.xlsx'
    recheckDf = pd.read_excel(recheck_file_path)
    print(recheckDf.columns)

    usedOrderIds = recheckDf["订单号"].tolist()


    df = pd.read_csv(file_name, sep='\001')
    df["order_id"] = df.apply(get_order_id,axis=1)
    df = df[df['order_id'].isin(usedOrderIds)]

    order_feature_dict = {
        order_id:feature for (order_id,feature) in
        zip(df["order_id"].tolist(),df["feature"].tolist())
    }

    def apply_get_result(item,feature_dict,check_label):
        # if item["订单号"] != 35409637838261926:
        #     j = 1
        #     return 1,1,1,1,1
        feature = json.loads(feature_dict[item["订单号"]])
        if "unreasonable" in feature:
            del feature["unreasonable"]



        newResult = get_juge_result(feature)

        newFeature = newResult["importantFeatureList"]
        newFeatureLog = newResult["judge_logger_info"]

        make_predict_sop(newFeatureLog, check_label)


        origin_result = "是" if   item["最终责任方"] in ["司机责任","双方责任"] else "否"

        new_result = "是" if check_label in str(newFeature) else "否"
        if_new_same = "一致" if new_result == origin_result else "不一致"
        if_old_same = "一致" if item["线上识别结果"] == origin_result else "不一致"
        return new_result,make_predict_sop(newFeatureLog, check_label),if_new_same,if_old_same

    recheckDf["新逻辑识别标签"],recheckDf["新逻辑识别标签SOP"],recheckDf["人工逻辑是否一致"],recheckDf["人工线上逻辑是否一致"] = zip(*recheckDf.apply(apply_get_result,axis=1,args=(order_feature_dict,check_label)))

    recheckDf['订单号'] = recheckDf["订单号"].apply(str)
    #recheckDf = recheckDf[list(recheckDf.columns) + ['人工逻辑是否一致',"人工线上逻辑是否一致"]]

    recheckDf.to_excel("result.xlsx")




if __name__ == '__main__':
    check_file = r'C:\Users\fengfeng.qiu\Downloads\20231107.csv'
    #online_data_check()
    need_types = ["司机没有主动联系货主"] #["司机抢错单","司机爽约","司机没有主动联系货主", "线下交易2"]
    for check in need_types:
        offline_data_check(check_file,check)
    #recheck(check_file,"司机抢错单")
